import difflib
import re
from typing import Union, Any

import pandas as pd


def handle_com_scale(x: str) -> str:
    """处理企业规模"""
    if "1-" in x:
        return "1-100人"
    elif "100-" in x:
        return "100-200人"
    elif "200-" in x:
        return "200-500人"
    elif "500-" in x:
        return "500-1000人"
    elif "1000-" in x:
        return "1000-2000人"
    elif "1000-" in x:
        return "1000-2000人"
    else:
        return "1-100人"


def handle_email(x: str) -> str:
    """处理邮箱"""
    email = re.search(r"[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+", str(x))
    if email:
        return email[0]
    else:
        return ""


def handle_phone(x: str) -> str:
    """处理手机号"""
    phone = re.search(r"[0-9]{11}", str(x))
    if phone:
        return phone[0]
    else:
        return ""


def handle_com_nature(x: str) -> str:
    """处理企业性质"""
    if "企业" or "中外合营" in x:
        return x
    elif "其他" in x:
        return "私营·民营企业"
    else:
        return x + '企业'


def handle_com_funds(x: str) -> str:
    """处理企业资金"""
    x = str(x)
    if "50万以下" in x:
        return "50万以下"
    elif "50万-" in x:
        return "50万-100万"
    elif "100万-" in x:
        return "100万-500万"
    elif "500万-" in x:
        return "500万-1000万"
    elif "1000万-" in x:
        return "1000万-5000万"
    elif "5000万以上" in x:
        return "5000万以上"
    else:
        return ""


def handle_num_recruits(x: str) -> str:
    """处理招聘人数"""
    x = str(x).replace("名", "").replace("若干", "10").replace("多", "10").replace("人", "")
    if not x:
        x = 10
    if int(x) > 1000:
        x = x[:-1]
    return x


def handle_degree(x: str) -> str:
    """处理学历"""
    if "初级中学" == x:
        return "初中及以下"
    elif "大学本科" == x:
        return "本科"
    elif "大学专科" == x:
        return "专科"
    elif "技工学校" == x:
        return "中专"
    else:
        return x


def handle_address(x: str) -> str:
    """处理人才网对于地址格式的需求"""
    x = x.replace("广东省", "").replace("广东", "")
    x = x.replace("东莞市", "")
    town_list = ["茶山镇", "常平镇", "大朗镇", "大岭山镇", "道滘镇", "东城区", "东城街道", "东坑镇", "凤岗镇", "高埗镇",
                 "莞城区", "莞城街道", "横沥镇", "洪梅镇", "厚街镇", "虎门镇", "黄江镇", "寮步镇", "麻涌镇", "南城区", "南城街道",
                 "企石镇", "桥头镇", "清溪镇", "沙田镇", "石碣镇", "石龙镇", "石排镇", "松山湖", "塘厦镇", "万江区", "万江街道", "望牛墩镇",
                 "谢岗镇", "樟木头镇", "长安镇", "中堂镇"]
    for town in town_list:
        if "/" in x:
            x = x.replace("/", "")
        if town in x:
            x = x.replace(town, "")
    x = x.replace("·", "")
    return x


def duties_request(duties: str, request: str) -> str:
    """处理岗位职责和要求"""
    if 'nan' not in duties and 'nan' not in request:
        return "岗位职责：\n" + duties.replace("岗位职责", "") + '\n' + '任职要求：\n' + request.replace("任职要求", "")
    elif 'nan' not in duties and 'nan' in request:
        return "岗位职责：\n" + duties.replace("岗位职责", "")
    elif 'nan' not in request and 'nan' in duties:
        return '任职要求：\n' + request.replace("任职要求", "")


class HandleComInfo:
    def __init__(self,
                 path="./data_folder/",
                 # path="/data/xxz_flask/data_folder/",
                 ):
        self.path = path
        self.data = pd.read_excel(self.path + '企业表处理.xlsx', header=1)
        self.data.columns = [i.replace("*", "") for i in self.data.columns]

    def general_handle(self) -> None:
        """通用的处理信息"""
        data = self.data
        data['招聘会id'] = ""
        data['专业要求'] = "不限"
        data['推荐渠道'] = '镇区推荐'
        data['工作性质'] = '全职'
        data['薪酬类型'] = '月薪'
        data['手机号'] = data['手机号'].apply(lambda x: handle_phone(x))
        # data['简历投递邮箱'] = data['简历投递邮箱'].apply(lambda x: handle_email(x))
        data['企业规模（选项）'] = data['企业规模（选项）'].apply(lambda x: handle_com_scale(str(x)))
        data['企业性质（选项）'] = data['企业性质（选项）'].apply(lambda x: handle_com_nature(x))
        data['注册资金（选项）'] = data['注册资金（选项）'].apply(lambda x: handle_com_funds(x))
        data['学历要求（选项）'] = data['学历要求（选项）'].apply(lambda x: handle_degree(x))
        data['推荐人'] = data['镇区'].apply(lambda x: x.replace("街道", "区"))
        data['所在地区'] = data['省份'] + "/" + data['城市'] + "/" + data['区县']
        data['工作地区'] = data['所在地区']
        data['招聘人数'] = data['招聘人数'].apply(lambda x: handle_num_recruits(x))
        data['最低薪资（元）'] = data['最低薪资（元）'].fillna(3000)
        data['职位描述'] = data.apply(lambda x: duties_request(str(x['岗位职责']), str(x['任职要求'])), axis=1)
        data = data.drop('序号', axis=1).reset_index().rename(columns={"index": "序号"})
        self.data = data

    def xxz_handle(self) -> None:
        """校校招处理"""
        data = self.data
        data = data.rename(columns={'Unnamed: 12': '企业所属行业（细类）', })
        print(data.columns)
        columns_name = ['序号', '招聘会id', '企业名称', '联系人', '性别', '职位', '手机号', '简历投递邮箱', '推荐渠道', '推荐人', '企业规模（选项）',
                        '企业性质（选项）', '企业所属行业（选项）', '企业所属行业（细类）', '所在地区', '详细地址', '注册资金（选项）', '企业简介', '职位名称',
                        '职位所属类别（选项）', 'Unnamed: 20', 'Unnamed: 21', '学历要求（选项）', '专业要求', '工作地区', '工作详细地址', '工作性质',
                        '薪酬类型', '最低薪资（元）', '最高薪资（元）', '招聘人数', '截至日期', '职位描述']
        data[columns_name].astype(str).to_excel(self.path + "xxz.xlsx", index=False)  # 导出校校招格式
        # print("校校招导出成功!")

    def job51_handle(self) -> None:
        """人才网处理"""
        data = self.data
        data['薪资'] = data.apply(lambda x: str(x['最低薪资（元）']).replace(".0", "") + '-' + str(x['最高薪资（元）']), axis=1)
        data['详细地址'] = data['所在地区'] + '/' + data['详细地址'].apply(lambda x: handle_address(x))
        data['工作经验'] = "不限"

        columns_talents = ['企业名称', '详细地址', '联系人', '手机号', '简历投递邮箱', '企业性质（选项）', '企业所属行业（选项）',
                           '企业规模（选项）', '企业简介', '职位名称', '招聘人数', '薪资', '工作经验',
                           '学历要求（选项）', '职位描述']
        # job51d_town_export(data_folder.astype(str), columns_talents)  # 分镇区导出
        data[columns_talents].astype(str).to_excel(self.path + "51job.xlsx", index=False)
        # print("人才网导出成功!")

    def fill_type(self) -> None:
        """校校招填充职位类别"""
        data = pd.read_excel(self.path + "xxz.xlsx")
        data[['职位所属类别（选项）', 'Unnamed: 20', 'Unnamed: 21']] = "NAN"
        data_map = pd.read_excel(self.path + "pos_name_guess_pos_type.xlsx")
        data_map['pos_type'] = data_map['pos_type'].apply(lambda x: x.replace('[', '').replace(']', '').split(',')[0])
        keys_ = [str(key) for key in data_map['keyword'].to_list()]
        dict_ = data_map.set_index('keyword')['pos_type'].to_dict()

        def map_fill(x: Any) -> Union[list, int]:
            try:
                x = dict_[x['职位名称']]
            except KeyError:
                x = difflib.get_close_matches(x['职位名称'], keys_)
                if x is list:
                    x = dict_[x[0]]
                else:
                    x = 10029999
            return x

        data['Unnamed: 21'] = data.apply(lambda x: map_fill(x), axis=1)
        data.to_excel(self.path + "xxz.xlsx", index=False)


if __name__ == "__main__":
    hci = HandleComInfo()
    hci.general_handle()
    hci.xxz_handle()
    hci.job51_handle()
